//% color="#296aa0" iconWidth=50 iconHeight=40
namespace XEduHub_main{

    //% block="XEduHub初始化 定义任务名[OBJ] 选择[MODULE]模型" blockType="command" 
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% MODULE.shadow="dropdownRound"    MODULE.options=MODULE
    export function XEduHub_main_init(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let MODULE = parameter.MODULE.code;

        let boardmenutype=parameter.MODULE.parType
        //console.log(boardmenutype)
        Generator.addInitHeader(`initpara${OBJ}`,`para_${OBJ} = {}`)

        if(boardmenutype.match("nick-xeduhub_main-thirdex.menu.XEduHub_main_init.MODULEMenu")!=null){
            
            Generator.addCode(`init_para_${OBJ} = {"task":"${MODULE}"}`)
        }else{
            Generator.addCode(`init_para_${OBJ} = {"task":${MODULE}}`)  
        }


    }

    //% block="设置任务[OBJ]的初始化高级参数[PARAM] 为[VAL]" blockType="command" 
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% PARAM.shadow="dropdownRound"    PARAM.options=PARAM
    //% VAL.shadow="normal"    VAL.defl=""
    export function XEduHub_main_init_set(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let PARAM = parameter.PARAM.code;
        let VAL = parameter.VAL.code;

        let boardmenutype=parameter.PARAM.parType
        
        if(PARAM=="download_path"){
            VAL =checkQuotes(VAL)
            VAL = `r${VAL}`
        }else if(PARAM=="checkpoint"){
            VAL =checkQuotes(VAL)
        }

        if(boardmenutype.match("nick-xeduhub_main-thirdex.menu.XEduHub_main_init_set.PARAM")!=null){
            Generator.addCode(`init_para_${OBJ}["${PARAM}"] = ${VAL}`)
        }else{
            Generator.addCode(`init_para_${OBJ}[${PARAM}] = ${VAL}`)
        }


    }

    
    //% block="任务[OBJ] 完成初始化" blockType="command" 
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_init_end(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addImport("from XEdu.hub import Workflow as wf\nimport os");
        Generator.addCode(`${OBJ} = wf(**init_para_${OBJ})`)

    }
    
    
    //% block="---"
    export function noteSep2() {

    }
    


    //% block="设置任务[OBJ]的推理参数[CONFIG]为[VAL]" blockType="command"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% CONFIG.shadow="dropdownRound"    CONFIG.options=CONFIG
    //% VAL.shadow="normal"    VAL.defl=""
    export function XEduHub_set_tuili(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let CONFIG = parameter.CONFIG.code;
        let boardmenutype=parameter.CONFIG.parType
        //console.log(boardmenutype)
        let VAL = parameter.VAL.code;
        

        if(CONFIG=="data"){
            VAL =addStrQuotation(VAL)
        }else if(CONFIG=="img_type"){
            if(VAL=='pil'||VAL=='cv2'){
                VAL = `"${VAL}"`
            }
        }

        if(boardmenutype.match("nick-xeduhub_main-thirdex.menu.XEduHub_set_tuili.CONFIGMenu")!=null){
            Generator.addCode(`para_${OBJ}["${CONFIG}"] = ${VAL}`)
        }else{
            Generator.addCode(`para_${OBJ}[${CONFIG}] = ${VAL}`)
        }

    }




    //% block="任务[OBJ]完成推理设置 进行一次推理" blockType="command"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_tuili(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addImport("import re");

        //Generator.addCode(`rea_result_${OBJ}= ${OBJ}.inference(**para_${OBJ})`)
        Generator.addImport("from XEdu.hub import Workflow as wf\nimport os");

        Generator.addCode(`
if '${OBJ}' in globals() or '${OBJ}' in locals():
    rea_result_${OBJ} = ${OBJ}.inference(**para_${OBJ})
else:
    print("init",'${OBJ}')
    ${OBJ} = wf(**init_para_${OBJ})
    rea_result_${OBJ} = ${OBJ}.inference(**para_${OBJ})
`)
    }
    //% block="---"
    export function noteSep() {

    }
    //% block="获取任务[OBJ]的推理原始输出" blockType="reporter"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_output(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addCode(`rea_result_${OBJ}`)
    }

    //% block="获取任务[OBJ]原始输出中[OUTPUT]" blockType="reporter"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% OUTPUT.shadow="dropdown"    OUTPUT.options=OUTPUT
    export function XEduHub_main_output_get_key(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let OUTPUT = parameter.OUTPUT.code;
        Generator.addDeclaration("XEduHub_main_output_getkey",`
def valve_getkey(result_val,result_key):
    val_len = len(result_val)
    if val_len<1:
        raise ValueError("Error:推理结果为空，请检查传入的图像或推理参数是否有问题。")
    if val_len==1 and result_key==1:
        raise ValueError("Error:推理结果中无图像，请检查推理参数中img_type项。")
    try: 
        return result_val[result_key]
    except Exception as e:
        raise ValueError(f"Error: 从推理原始结果中取值错误。result_val:{result_val}, result_key:{result_key}。\\nException:{e} ")
`)
        
       
            Generator.addCode(`valve_getkey(rea_result_${OBJ},${OUTPUT})`)
        
    }


    //% block="---"
    export function noteSep4() {

    }

    //% block="将任务[OBJ]的推理结果格式化" blockType="command"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_format_output(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addImport("import sys");
        /*
        Generator.addDeclaration("XEduHub_main_format_output",`
def get_format_output(result_input, result_index):
    try:
        # 尝试返回请求的键对应的值
        return result_input[str(result_index)]
    except KeyError:
        # 如果键不存在于字典中，则捕获KeyError
        return f"KeyError: '{result_index}' 不是有效的键"
    except TypeError:
        # 如果提供的索引不是整数，则捕获TypeError
        return "TypeError: 格式化异常"
`)*/
        Generator.addDeclaration("XEduHub_main_format_output",`
def format_valve_output(task):
    try:
        output_result = ""
        output_result = task.format_output(lang="zh")
        return output_result
    except AttributeError:
        return "AttributeError: 请检查输入数据是否正确"`)
  
        Generator.addCode(`output_result_${OBJ} = format_valve_output(${OBJ})`)

    }

    //% block="获取任务[OBJ]格式化后的所有结果" blockType="reporter"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_get_format_output(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addCode(`output_result_${OBJ}`)
    }

    //% block="获取任务[OBJ]格式化后的结果中[KEY]的值" blockType="reporter"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% KEY.shadow="string"    KEY.defl="分数"
    export function XEduHub_main_get_format_output_getkey(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let KEY = parameter.KEY.code;
       
            Generator.addCode(`output_result_${OBJ}[${KEY}]`)
        
    }



        //% block="---"
        export function noteSep3() {

        }
    //% block="显示任务[OBJ]的结果可视化图片" blockType="command"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    export function XEduHub_main_show(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        Generator.addCode(`${OBJ}.show(rea_result_${OBJ})`)
    }


    //% block="保存任务[OBJ]的推理结果图片到[DIR]" blockType="command"
    //% OBJ.shadow="normal"    OBJ.defl=task1
    //% DIR.shadow="string"    DIR.defl='cls_result.jpg'
    export function XEduHub_main_save(parameter: any, block: any){
        let OBJ = parameter.OBJ.code;
        let DIR = parameter.DIR.code;
        Generator.addCode(`${OBJ}.save(rea_result_${OBJ},${DIR})`)
    }






        function addStrQuotation(input_str: string): string {
            //后缀为图片的增加引号
            const dotIndex = input_str.lastIndexOf('.');
            if (dotIndex === -1) {
                return input_str;
            }
            const substringAfterDot = input_str.slice(dotIndex + 1);
            if (substringAfterDot === 'png' || substringAfterDot === 'jpg'){
                return `"${input_str}"`;
            }
            else{
                return input_str;
            }

        }
        //检查是否引号结束
        function checkQuotes(inputstr: string): string {
            const firstChar = inputstr.charAt(0);
            const lastChar = inputstr.charAt(inputstr.length - 1);
          
            if( (firstChar === "'" || firstChar === '"') && firstChar === lastChar){
                return inputstr
            }else{
                return `"${inputstr}"`
            }

          }

}
